import { View, Text, Button } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro, { useLoad, useRouter } from '@tarojs/taro'
import './index.less'

export default function OrderDetail() {
  const router = useRouter()
  const [order, setOrder] = useState(null)
  const [loading, setLoading] = useState(true)

  const statusSteps = [
    { key: 'pending', title: '订单确认', desc: '订单已提交，等待确认' },
    { key: 'picked', title: '衣物取件', desc: '衣物已取件，准备洗护' },
    { key: 'washing', title: '洗护处理', desc: '衣物正在洗护中' },
    { key: 'ready', title: '洗护完成', desc: '衣物洗护完成，可以取回' },
    { key: 'completed', title: '订单完成', desc: '衣物已取回，订单完成' }
  ]

  const statusMap = {
    'pending': '待取件',
    'picked': '已取件',
    'washing': '洗护中',
    'ready': '待取回',
    'completed': '已完成'
  }

  const serviceTypeMap = {
    'wash': '普通洗涤',
    'dry-clean': '干洗',
    'repair': '修补'
  }

  useLoad(() => {
    const orderId = router.params.id
    if (orderId) {
      loadOrderDetail(orderId)
    }
  })

  const loadOrderDetail = (orderId) => {
    try {
      const orders = Taro.getStorageSync('orders') || []
      const orderInfo = orders.find(item => item.id === orderId)
      if (orderInfo) {
        setOrder(orderInfo)
      } else {
        Taro.showToast({ title: '订单不存在', icon: 'none' })
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      }
    } catch (error) {
      Taro.showToast({ title: '获取订单失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  const getCurrentStepIndex = () => {
    if (!order) return 0
    return statusSteps.findIndex(step => step.key === order.status)
  }

  const handlePayment = () => {
    Taro.navigateTo({
      url: `/pages/payment/index?type=order&orderId=${order.id}&amount=${order.price}`
    })
  }

  const handleContact = () => {
    Taro.makePhoneCall({
      phoneNumber: '400-123-4567'
    })
  }

  const copyPickupCode = () => {
    Taro.setClipboardData({
      data: order.pickupCode,
      success: () => {
        Taro.showToast({ title: '取件码已复制', icon: 'success' })
      }
    })
  }

  if (loading) {
    return (
      <View className='loading-container'>
        <Text>加载中...</Text>
      </View>
    )
  }

  if (!order) {
    return (
      <View className='error-container'>
        <Text>订单不存在</Text>
      </View>
    )
  }

  const currentStepIndex = getCurrentStepIndex()

  return (
    <View className='order-detail-page'>
      {/* 订单状态 */}
      <View className='status-section'>
        <View className='status-header'>
          <Text className='status-title'>{statusMap[order.status]}</Text>
          <Text className='status-desc'>
            {statusSteps[currentStepIndex]?.desc || '订单处理中'}
          </Text>
        </View>
        
        {/* 进度条 */}
        <View className='progress-container'>
          {statusSteps.map((step, index) => (
            <View key={step.key} className='progress-item'>
              <View className={`progress-dot ${index <= currentStepIndex ? 'active' : ''}`}>
                {index <= currentStepIndex ? '✓' : index + 1}
              </View>
              <View className='progress-content'>
                <Text className={`progress-title ${index <= currentStepIndex ? 'active' : ''}`}>
                  {step.title}
                </Text>
                {index === currentStepIndex && (
                  <Text className='progress-desc'>{step.desc}</Text>
                )}
              </View>
              {index < statusSteps.length - 1 && (
                <View className={`progress-line ${index < currentStepIndex ? 'active' : ''}`}></View>
              )}
            </View>
          ))}
        </View>
      </View>

      {/* 取件码 */}
      {order.pickupCode && (
        <View className='pickup-code-section'>
          <Text className='section-title'>取件码</Text>
          <View className='pickup-code-card' onClick={copyPickupCode}>
            <Text className='pickup-code-number'>{order.pickupCode}</Text>
            <Text className='pickup-code-tip'>点击复制取件码</Text>
          </View>
        </View>
      )}

      {/* 订单信息 */}
      <View className='order-info-section'>
        <Text className='section-title'>订单信息</Text>
        <View className='info-card'>
          <View className='info-row'>
            <Text className='info-label'>订单号</Text>
            <Text className='info-value'>{order.id}</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>服务类型</Text>
            <Text className='info-value'>
              {order.type === 'pickup' ? '上门取件' : '到店取件'}
            </Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>洗护项目</Text>
            <Text className='info-value'>{serviceTypeMap[order.serviceType]}</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>衣物数量</Text>
            <Text className='info-value'>{order.clothesCount}件</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>服务地址</Text>
            <Text className='info-value'>{order.address}</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>联系人</Text>
            <Text className='info-value'>{order.contact}</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>联系电话</Text>
            <Text className='info-value'>{order.phone}</Text>
          </View>
          <View className='info-row'>
            <Text className='info-label'>预约时间</Text>
            <Text className='info-value'>{order.pickupDate} {order.pickupTime}</Text>
          </View>
          {order.remark && (
            <View className='info-row'>
              <Text className='info-label'>备注</Text>
              <Text className='info-value'>{order.remark}</Text>
            </View>
          )}
          <View className='info-row'>
            <Text className='info-label'>下单时间</Text>
            <Text className='info-value'>{order.createTime}</Text>
          </View>
          {order.payTime && (
            <View className='info-row'>
              <Text className='info-label'>支付时间</Text>
              <Text className='info-value'>{order.payTime}</Text>
            </View>
          )}
        </View>
      </View>

      {/* 费用明细 */}
      <View className='cost-section'>
        <Text className='section-title'>费用明细</Text>
        <View className='cost-card'>
          <View className='cost-row'>
            <Text className='cost-label'>服务费用</Text>
            <Text className='cost-value'>¥{order.price}</Text>
          </View>
          <View className='cost-row total'>
            <Text className='cost-label'>实付金额</Text>
            <Text className='cost-value total-amount'>¥{order.price}</Text>
          </View>
        </View>
      </View>

      {/* 操作按钮 */}
      <View className='action-section'>
        {order.status === 'pending' && (
          <Button 
            type='primary'
            className='action-btn'
            onClick={handlePayment}
          >
            立即支付
          </Button>
        )}
        <Button 
          className='action-btn secondary'
          onClick={handleContact}
        >
          联系客服
        </Button>
      </View>
    </View>
  )
}